<template>
  <a-row>
    <a-col :span="11">
      <a-month-picker
        :value="startTime"
        :placeholder="placeholder[0]"
        :valueFormat="valueFormat"
        @change="handleStartTimeChange"
        allowClear
        style="width: 100%;"
        :disabledDate="disabledStartMonth"
      />
    </a-col>
    <a-col :span="2" style="text-align: center">~</a-col>
    <a-col :span="11">
      <a-month-picker
        :value="endTime"
        :placeholder="placeholder[1]"
        :valueFormat="valueFormat"
        @change="handleendTimeChange"
        allowClear
        style="width: 100%;"
        :disabledDate="disabledEndMonth"
      />
    </a-col>
  </a-row>
</template>
<script>
import moment from 'moment'

export default {
  name: 'MonthRange',
  props: {
    value: {
      type: Array,
      required: false
    },
    placeholder: {
      type: Array,
      default: () => ['开始月份', '结束月份']
    },
    valueFormat: {
      type: String,
      default: 'YYYY-MM'
    },
    format: {
      type: String,
      default: 'YYYY-MM'
    }
  },
  data() {
    return {
      open: false,
      startTime: undefined,
      endTime: undefined
    }
  },
  methods: {
    disabledStartMonth(val) {
      if (!this.endTime) return false
      return (
        val.valueOf() >
        moment(this.endTime)
          .endOf('month')
          .valueOf()
      )
    },
    disabledEndMonth(val) {
      if (!this.startTime) return false
      return (
        val.valueOf() <
        moment(this.startTime)
          .startOf('month')
          .valueOf()
      )
    },
    handleStartTimeChange(value) {
      this.startTime = value
      this.triggerChange()
    },
    handleendTimeChange(value) {
      this.endTime = value
      this.triggerChange()
    },
    triggerChange() {
      const { startTime, endTime } = this
      if ((!startTime || !endTime) && this.value) {
        this.$emit('change', undefined)
      } else {
        this.$emit('change', [startTime, endTime])
      }
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  watch: {
    value(val) {
      if (val && Array.isArray(val)) {
        const [startTime, endTime] = val
        this.startTime = startTime
        this.endTime = endTime
      } else {
        this.startTime = undefined
        this.endTime = undefined
      }
    }
  }
}
</script>
